package br.com.mmm.javacenter.framework.reflection;

import java.lang.reflect.Field;
import java.util.Calendar;
import java.util.List;

import javax.persistence.Column;

import br.com.mmm.javacenter.framework.annotations.AttributeTagSupport;
import br.com.mmm.javacenter.framework.annotations.GenericTagSupport;
import br.com.mmm.javacenter.framework.entity.EntidadeBase;

public class FieldAdapter {
	private Field field;
	private EntidadeBase entidadeBase;
	
	
	public Field getField() {
		return field;
	}
	public void setField(Field field) {
		this.field = field;
	}
	public FieldAdapter(Field field) {
		super();
		this.field = field;
	}
	public FieldAdapter(Field f, EntidadeBase entidadeBase) {
		this.field = f;
		this.entidadeBase = entidadeBase;
	}
	public String getName(){
		return field.getName();
	}
	public String getLabel(){
		GenericTagSupport annotation = field.getAnnotation(GenericTagSupport.class);
		if(annotation!=null){
			AttributeTagSupport[] attributes = annotation.value();
			for(AttributeTagSupport attributeTagSupport:attributes){
				if(attributeTagSupport.name().equals("label")){
					return attributeTagSupport.value();
				}
			}
		}
		return getName();
	}
	public int getLength(){
		Column column = field.getAnnotation(Column.class);
		if(column==null){
			if(field.getType() == String.class){
				return 255;
			}else if(field.getType() == Integer.class || field.getType() == int.class){
				return String.valueOf(Integer.MAX_VALUE).length();
			}else if(field.getType() == long.class || field.getType() == Long.class){
				return String.valueOf(Long.MAX_VALUE).length();
			}else if(field.getType() == double.class || field.getType() == Double.class){
				return String.valueOf(Double.MAX_VALUE).length();
			}else if(field.getType() == Float.class || field.getType() == float.class){
				return String.valueOf(Float.MAX_VALUE).length();
			}else if(field.getType() == Integer.class || field.getType() == int.class){
				return String.valueOf(Integer.MAX_VALUE).length();
			}else if(field.getType() == Calendar.class || field.getType() == java.util.Date.class){
				return 10;
			}else{
				return 10;
			}
		}else{
			return column.length();
		}
	}
	public List<EntidadeBase> getList(){
		ReflectionFacade rf = new ReflectionFacade(entidadeBase);
		return (List<EntidadeBase>) rf.get(field.getName());
	}

}
